package com.easy.Data;
import java.sql.*;
import java.net.*;
import java.io.*;
import org.json.*;

    public class AmapAttractionFetcher {

        private static final String AMAP_KEY = "0c8241f57df8da93d4346283bbf6abe8";
        private static final String CITY = "北京";
        private static final String KEYWORDS = "景点";
        private static final int PAGE_SIZE = 20;
        private static final int MAX_PAGE = 5;

        private static final String DB_URL = "jdbc:mysql://localhost:3306/easy0812";
        private static final String DB_USER = "root";
        private static final String DB_PASSWORD = "287052";

        private Connection conn;

        public AmapAttractionFetcher() throws Exception {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        }

        public boolean isExist(String name, String city) throws SQLException {
            String sql = "SELECT COUNT(*) FROM attraction WHERE name=? AND city=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, name);
                ps.setString(2, city);
                ResultSet rs = ps.executeQuery();
                rs.next();
                return rs.getInt(1) > 0;
            }
        }

        public void saveToDB(String name, String city, String type, String desc, String lat, String lng) {
            try {
                if (isExist(name, city)) {
                    System.out.println("[SKIP] 已存在景点：" + name);
                    return;
                }
                String sql = "INSERT INTO attraction (name, city, type, description, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?)";
                try (PreparedStatement ps = conn.prepareStatement(sql)) {
                    ps.setString(1, name);
                    ps.setString(2, city);
                    ps.setString(3, type);
                    ps.setString(4, desc);
                    ps.setString(5, lat);
                    ps.setString(6, lng);
                    ps.executeUpdate();
                    System.out.println("[OK] 已插入景点：" + name);
                }
            } catch (Exception e) {
                System.out.println("[ERROR] 插入失败：" + e.getMessage());
            }
        }

        public void fetchPOI() throws Exception {
            for (int page = 1; page <= MAX_PAGE; page++) {
                String urlStr = String.format(
                        "https://restapi.amap.com/v3/place/text?key=%s&keywords=%s&city=%s&page=%d&offset=%d&output=JSON",
                        AMAP_KEY, URLEncoder.encode(KEYWORDS, "UTF-8"), URLEncoder.encode(CITY, "UTF-8"), page, PAGE_SIZE
                );

                String json = get(urlStr);
                JSONObject obj = new JSONObject(json);
                if (obj.has("pois")) {
                    JSONArray pois = obj.getJSONArray("pois");
                    for (int i = 0; i < pois.length(); i++) {
                        JSONObject poi = pois.getJSONObject(i);
                        String name = poi.optString("name", "");
                        String type = poi.optString("type", "");
                        String desc = poi.optString("address", "");
                        String location = poi.optString("location", "");
                        String lat = null, lng = null;
                        if (!location.isEmpty()) {
                            String[] arr = location.split(",");
                            lng = arr[0];
                            lat = arr[1];
                        }
                        saveToDB(name, CITY, type, desc, lat, lng);
                    }
                }
                Thread.sleep(500);
            }
        }

        private String get(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            return content.toString();
        }

        public static void main(String[] args) throws Exception {
            AmapAttractionFetcher fetcher = new AmapAttractionFetcher();
            fetcher.fetchPOI();
            System.out.println("数据采集完成！");
        }
    }


